package com.neusoft.work.service.impl;

import java.util.List;
import java.util.stream.Collectors;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.neusoft.work.dao.CareProjectDao;
import com.neusoft.work.dao.CustomerCarePlanDao;
import com.neusoft.work.dao.CustomerDao;
import com.neusoft.work.dto.CustomerCarePlanDTO;
import com.neusoft.work.po.CareProject;
import com.neusoft.work.po.Customer;
import com.neusoft.work.po.CustomerCarePlan;
import com.neusoft.work.po.PageResponseBean;
import com.neusoft.work.po.ResponseBean;
import com.neusoft.work.service.CustomerCarePlanService;

@Service
public class CustomerCarePlanServiceImpl implements CustomerCarePlanService {

    @Autowired
    private CustomerCarePlanDao customerCarePlanDao;
    @Autowired
    private CustomerDao customerDao;
    @Autowired
    private CareProjectDao careProjectDao;  // 新增：注入项目 DAO

    @Override
    public ResponseBean<List<Customer>> searchCustomer(String customerName) {
        // 模糊查询客户
        List<Customer> list = customerDao.selectList(
            new QueryWrapper<Customer>()
                .like("name", customerName == null ? "" : customerName.trim())
                .eq("isDeleted", false)
        );
        return new ResponseBean<>(list);
    }

    @Override
    public ResponseBean<List<CustomerCarePlanDTO>> searchCustomerCarePlan(Integer customerId) {
        // 1. 查出这个客户的所有计划
        List<CustomerCarePlan> plans = customerCarePlanDao.selectList(
            new QueryWrapper<CustomerCarePlan>()
                .eq("customerId", customerId)
        );

        // 2. 对每条计划，去 CareProject 表找名称和价格
        List<CustomerCarePlanDTO> dtoList = plans.stream().map(p -> {
            CustomerCarePlanDTO dto = new CustomerCarePlanDTO();
            // 拷贝通用字段
            dto.setId(p.getId());
            dto.setCustomerId(p.getCustomerId());
            dto.setCareProjectCode(p.getCareProjectCode());
            dto.setPurchaseDate(p.getPurchaseDate());
            dto.setQuantity(p.getQuantity());
            dto.setExpireDate(p.getExpireDate());
            dto.setStatus(p.getStatus());
            dto.setSource(p.getSource());

            // 根据 code 去查询项目名称和价格
            CareProject cp = careProjectDao.selectOne(
                new QueryWrapper<CareProject>().eq("code", p.getCareProjectCode())
            );
            if (cp != null) {
            	dto.setProjectId(cp.getId());
                dto.setProjectName(cp.getName());
                dto.setPrice(cp.getPrice());
            } else {
                dto.setProjectName("未知项目");
                dto.setPrice(0.0);
            }
            return dto;
        }).collect(Collectors.toList());

        return new ResponseBean<>(dtoList);
    }

    @Override
    public ResponseBean<Integer> addCustomerCarePlan(CustomerCarePlan ccp) {
    	int rows = customerCarePlanDao.insert(ccp);
        if (rows > 0) {
            // 设置客户为护理老人
            Customer customer = new Customer();
            customer.setId(ccp.getCustomerId());
            customer.setType(2);  // 2=护理老人
            customerDao.updateById(customer);

            return new ResponseBean<>(ccp.getId());
        } else {
            return new ResponseBean<>(500, "添加护理项目计划失败");
        }
    }

    @Override
    public ResponseBean<Integer> updateCustomerCarePlan(CustomerCarePlan ccp) {
    	System.out.println(ccp.getId());
        int rows = customerCarePlanDao.updateById(ccp);
        if (rows > 0) {
            return new ResponseBean<>(ccp.getId());
        } else {
            return new ResponseBean<>(500, "更新护理项目计划失败");
        }
    }

    @Override
    @Transactional
    public ResponseBean<Integer> delCustomerCarePlan(Integer customerId,String careProjectCode) {
    	// 删除指定护理项目
        int rows = customerCarePlanDao.delete(
            new QueryWrapper<CustomerCarePlan>()
                .eq("customerId", customerId)
                .eq("careProjectCode", careProjectCode)
        );

        // 判断是否还有护理项目，如果没有，就改为自理老人（type=1）
        Long count = customerCarePlanDao.selectCount(
            new QueryWrapper<CustomerCarePlan>()
                .eq("customerId", customerId)
                .eq("status", 1)  // 有效护理项目
        );
        Customer customer = new Customer();
        customer.setId(customerId);
        customer.setType(count > 0 ? 2 : 1);  // 2=护理，1=自理
        customerDao.updateById(customer);

        if (rows > 0) {
            return new ResponseBean<>(rows);
        } else {
            return new ResponseBean<>(500, "删除护理项目计划失败");
        }
    }
    
    @Override
    public PageResponseBean<List<CustomerCarePlanDTO>> searchCustomerCarePlan(
            Integer customerId, Long cur, Long number) {
        // 构造分页和查询条件
        Page<CustomerCarePlan> page = new Page<>(cur, number);
        QueryWrapper<CustomerCarePlan> qw = new QueryWrapper<CustomerCarePlan>().eq("customerId", customerId);
        IPage<CustomerCarePlan> result = customerCarePlanDao.selectPage(page, qw);

        // 转 DTO 并补全项目名称/价格
        List<CustomerCarePlanDTO> dtos = result.getRecords().stream().map(po -> {
            CustomerCarePlanDTO dto = new CustomerCarePlanDTO();
            BeanUtils.copyProperties(po, dto);
            CareProject proj = careProjectDao.selectOne(
                new QueryWrapper<CareProject>().eq("code", po.getCareProjectCode()));
            dto.setProjectId(proj.getId());
            dto.setProjectName(proj.getName());
            dto.setPrice(proj.getPrice());
            return dto;
        }).collect(Collectors.toList());

        // 返回分页结果
        PageResponseBean<List<CustomerCarePlanDTO>> rb = new PageResponseBean<>(dtos);
        rb.setTotal(result.getTotal());
        return rb;
    }
}
